package com.rytong.tools.ui;

import java.util.ArrayList;
import com.rytong.tools.ui.CssStyle;
import com.rytong.tools.utils.LPToastUtil;
import com.rytong.tools.utils.Utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint.Style;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.RadioButton;

public class LPRadio extends Component {
    /** Radio box images */
	public static Bitmap checkedImg_;
	public static Bitmap unCheckedImg_;

    private int TEXT_MARGIN = 10; // will add image width
    private Activity activity_;

    private String attrSearchkey_;
    public boolean isradiohiden = false ; 
    
    // 默认图标宽度。
    //private static final int BG_WIDTH_ = Utils.getScaledValueX(35);
    public class MyLPRadio extends RadioButton implements CompositedComponent {

        public MyLPRadio(Context context, String value) {
            super(context);
            setFocusable(true);
            setFocusableInTouchMode(true);
            setText(value);
            if(null != getPropertyByName("radiohiden") && getPropertyByName("radiohiden").equalsIgnoreCase("true")){
            	isradiohiden = true;
            }
            if (null != getPropertyByName("checked") && getPropertyByName("checked").equals("checked")) {
            	//先读取报文checked 属性
            	if (null != getPropertyByName("checked")) {
            	    if(getPropertyByName("checked").equals("checked")){
            	        setChecked(true);
            	        setPropertyByName("checked", "true");
            	    } else {
            	        setPropertyByName("checked", "false");
            	    }
            	} else {
            	    //报文没有给checked属性时
            	    setPropertyByName("checked", "false");
            	}
            }
        }

        @Override
        protected void onDraw(Canvas canvas) {
            if (null != searchkey()) {
                paintSearchKey(canvas, 0, 0);
            }else{
                drawRadio(canvas, 0, 0);
            }
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            int action = event.getAction();
            boolean isAction = false;
            switch (action) {
            case KeyEvent.ACTION_DOWN:
            	// 按下tr时候变色。
            	trDownColor(tr_, llvSV_);
                yDown_ = event.getY();
                this.requestFocus();
                isAction = true;
                break;
            case MotionEvent.ACTION_MOVE:
            	// 移动tr恢复颜色。
            	int offset = (int) Math.abs(yDown_ - event.getY());
            	if (offset > offset_) {
            		trMoveColor(tr_, llvSV_);
            	}
                break;
            case KeyEvent.ACTION_UP:
            	// 抬起tr恢复颜色。
            	trUpColor(tr_, llvSV_);
                setSelectedRadio();
                //控件联动
                setVisibleInvisible();
                isAction = onClick((String) composited().property_.get("onclick"));
                break;
            default:
                isAction = super.onTouchEvent(event);
            }
            return isAction;
        }

        /**
         * Derived class may change how text is drawn.
         */
        protected void drawRadio(Canvas g, int x, int y) {
            int bg_w = 0;
            Bitmap temp = null;
            if (isChecked()) {
                temp = checkedImg_;
            } else {
                temp = unCheckedImg_;
            }
            try {
            	if (temp != null && isradiohiden != true) {
            		g.drawBitmap(temp, x, (getHeight() - temp.getHeight()) / 2, getPaint()); // 先画背景图。
            		bg_w = temp.getWidth(); // 背景图的宽度。
            	}
            } catch (Exception ex) {
            	Utils.printException(ex);
            }

            int aw = getWidth() - bg_w-TEXT_MARGIN;
            int w = 0;
            if(null != getPaint()){
            	w = (int) getPaint().measureText((String) getText());            	
            }
            //跑马灯效果
            if (null != getPropertyByName("loop") && getPropertyByName("loop").toString().equalsIgnoreCase("true") 
            		&& isChecked() && w > aw) {
            	drawMoveStr(this, g, getWidth(), getPaint(), (String)getText(), bg_w+TEXT_MARGIN, ((int) (getHeight() + getPaint().getTextSize()) >> 1) - 2);
            }else{
                x += bg_w + TEXT_MARGIN; // 文字左边距是图宽度加上文字间隔。
                // 如果文字有多行，就进行分行绘制。
                if(stringArr_ != null && stringArr_.length > 1){
                	// int text_height = (int) paint_.getTextSize();// 文字高度
                    int text_height = ((int) (getPaint().getTextSize() * 3)) >> 2;
                    int length = stringArr_.length;
                    // 初始高度为留白高+字高
                    float coordinate_y = Utils.getScaledValueY(blankY_) + text_height;
                    /**
                     * 多行文字呈自然段，需要进行字间距的绘制。
                     */
                    float charPadding = 0;
                    for (int i = 0; i < length; i++) {
                    	if(stringArr_[i].endsWith("\n")){
            				charPadding = (maxLineWidth_ - 
            						getPaint().measureText(stringArr_[i].substring(0, stringArr_[i].lastIndexOf("\n")))) /
            						(stringArr_[i].substring(0, stringArr_[i].lastIndexOf("\n")).length() - 1);
            			} else {
            				charPadding = (maxLineWidth_ - getPaint().measureText(stringArr_[i])) / (stringArr_[i].length() - 1);
            			}
                    	if(i == length - 1 || stringArr_[i].endsWith("\n")){ // 最后一行和自然段尾行不计算字间距。
            				charPadding = 0;
            			}
                        if (i > 0)
                            coordinate_y += text_height + Utils.getScaledValueY(SPACE_Y_);
                        char[] charArray = stringArr_[i].toCharArray();
    					for (int j = 0; j < charArray.length; j++) {
    						if(charArray[j] != '\n'){
    							if(j == 0){
    								g.drawText(charArray, j, 1, x, coordinate_y, getPaint());
    							} else {
    								g.drawText(charArray, j, 1, 
    										x + charPadding * j + getPaint().measureText(stringArr_[i].substring(0, j)), 
    										coordinate_y, getPaint());
    							}
    						}
    					}
    					charArray = null;
//                        g.drawText(stringArr_[i], x, coordinate_y, getPaint());
                    }
                } else {
                	y = ((int) (getHeight() + getPaint().getTextSize()) >> 1) - 2;
                	String text = (String)getText();
                	if (text != null && !text.equals("")) {
                		g.drawText(text, x, y, getPaint());
                	}
                }
            }
        }
        /**
         * 绘制带有searchkey属性的控件效果
         * 
         * @param g
         * @param x
         * @param y
         */
        private void paintSearchKey(Canvas g, int x, int y) {
            int textColor = 0;
            CssStyle cs = cssStyle();
            if (cs != null) {
                textColor = fgColor();
            } else {
                try {
                    textColor = getTextColors().getDefaultColor();
                } catch (Exception e) {
                    textColor = getCurrentTextColor();
                }
            }
            paint_.setColor(textColor);
            paint_.setAntiAlias(true);
            int h = getIconSize(); // 拿到图标的高度，默认图标是正方形的。
            x += h + TEXT_MARGIN; // 左边距一开始设置为图标宽度加上文字的间隔。
            String text = property_.get("text");
            if (text == null) {
                return;
            }
            if (isFocused()) {
            	paint_.setColor(HL_BACKGROUND_COLOR);
            	int w = (int) ((paint_.measureText(text) + x) < (width_ - h - 10) ? paint_.measureText(text) + x
            			: (width_ - h - 10));
            	paint_.setStyle(Style.FILL);
            	g.drawRect(x, y, w + x, h + y + 2, paint_);
            	drawMoveStr(this, g, w, paint_, text, x, y + h);
            } else {
            	g.drawText(Utils.abbrevString(text, paint_, width_ - h - 10), x, y + h, paint_);
            }

        }

        /**
         * @return
         */
        private int getIconSize() {
            return (int) (paint_.getTextSize());
        }

        @Override
        public Component composited() {
            return LPRadio.this;
        }
    }

    /** create radio images */
    public final void setRadioBoxIcons() {
        try {
        	if(checkedImg_ == null || checkedImg_.isRecycled()){
				int checkedBg_Id = Utils.getResourcesId(activity_,
						"radio_checked", "drawable");
				checkedImg_ = Utils.getBitmap(checkedBg_Id, activity_);
				//checkedImg_ = Bitmap.createScaledBitmap(checkedImg_,Utils.getScaledValueX(checkedImg_.getWidth()),Utils.getScaledValueX(checkedImg_.getHeight()),true);
        	}

			if (unCheckedImg_ == null || unCheckedImg_.isRecycled()) {
				int unCheckedBg_Id = Utils.getResourcesId(activity_,
						"radio_unchecked", "drawable");
				unCheckedImg_ = Utils.getBitmap(unCheckedBg_Id, activity_);
				//unCheckedImg_ = Bitmap.createScaledBitmap(unCheckedImg_,Utils.getScaledValueX(unCheckedImg_.getWidth()),Utils.getScaledValueX(unCheckedImg_.getHeight()),true);
			}
        } catch (Exception ex) {
            Utils.printException(ex);
        }
    }

    /**
     * 控件联动方法
     * @param lpSelect
     * @param option
     */
    public void setVisibleInvisible(){
    	if(LPToastUtil.getInstance().isBranchBank){
    		String invisible = getPropertyByName("invisible");
    		String visible = getPropertyByName("visible");
    		Utils.setCompontentsLinked(visible, invisible);
    	}
    }
    
    /**
     * Checks all the radios in the view, and sets those in the same group unchecked.
     */
    public void setSelectedRadio() {
        final int size = radioList_.size();
        LPRadio radio;
        String name;
        String thisname = (String) getPropertyByName("name");
        for (int i = 0; i < size; i++) {
            radio = radioList_.get(i);
            name = (String) radio.getPropertyByName("name");
            if (name != null && name.equals(thisname)) {
                radio.setChecked(false);
                radio.setPropertyByName("checked", "false");
                radio.invalidate();
            }

        }
        setChecked(true);
        setStart(0);
        setPropertyByName("checked", "true");
        invalidate();
    }

    private void setChecked(boolean b) {
        MyLPRadio temp = (MyLPRadio) realView_;
        temp.setChecked(b);
    }

    /**
     * @param attrSearchkey_
     *            the attrSearchkey_ to set
     */
    public void setSearchkey(String attrSearchkey_) {
        this.attrSearchkey_ = attrSearchkey_;
    }

    /**
     * @return the attrSearchkey_
     */
    public String searchkey() {
        return attrSearchkey_;
    }

    /**
     * @return
     */
    public boolean isChecked() {
        MyLPRadio rd = (MyLPRadio) realView_;
        return rd.isChecked();
    }

    @Override
    public void initRealView(Activity activity, String value) {
        super.initRealView(activity, value);
        realView_ = new MyLPRadio(activity, value);
        activity_ = activity;
        if (radioList_ == null) {
            radioList_ = new ArrayList<LPRadio>();
        }
        radioList_.add(this);
    }

    public void mouldH() throws Exception {
        super.mouldH();
        setRadioBoxIcons();
        // 如果不含有searchKey，就进行分行判断。
        if(null == searchkey() && (null == getPropertyByName("loop") || "".equalsIgnoreCase(getPropertyByName("loop"))) 
        		&& checkedImg_ != null && unCheckedImg_ != null){
        	reSetTextLayoutParams(checkedImg_.getWidth() + TEXT_MARGIN);
        }
        if (null != cssStyle_) {
            mouldCssStyle();
        }
    }

    @Override
    public void mouldCssStyle() {
    	super.mouldCssStyle();
    	if (cssStyle_.getPropertyIndex(CssStyle.BGIMAGEURL) > cssStyle_.getPropertyIndex(CssStyle.BACKGROUNDCOLOR)) {
    	    setBackgroundDrawableByCssStyle();
    	} else {
    	    setBackgroundColorByCssStyle();
    	}
    }
    
    @Override
    public String getPropertyByName(String key) {
        if (radioList_ != null && key != null && key.equals("value")) {
            String thisname = (String) getPropertyByName("name");
            String name;
            LPRadio radio = null;
            boolean isChecked = false;
            int size = radioList_.size();
            for (int i = 0; i < size; i++) {
                radio = radioList_.get(i);
                name = (String) radio.getPropertyByName("name");
                isChecked = radio.isChecked();
                if (name != null && name.equals(thisname) && isChecked) {
                    break;
                } else {
                    radio = null;
                }
            }
            if (radio != null) {
                String value = radio.property_.get(key);
                return value == null ? "" : value;
            } else {
                return "";
            }
        } else {
            return super.getPropertyByName(key);
        }
    }

    @Override
    public void releaseResource(Component component) {
    	// TODO Auto-generated method stub
//    	Utils.releaseObject(checkedImg_);
//    	Utils.releaseObject(unCheckedImg_);
    }
}
